import React, { PureComponent } from 'react'
import { Button, Form, Input, InputNumber, Select, Icon, Alert, Tree, notification } from 'antd'
import Modal from 'kenote-react-admin-modal'
import QueueAnim from 'rc-queue-anim'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { passportActions } from 'reduxs'
import _ from 'lodash'
import 'styles/modal.scss'
import { getSiderMenus, getPageFlag, getFlagValue } from 'services/utils'
import * as menuSubs from 'features/menuSub'

const FormItem = Form.Item
const Option = Select.Option
const TextArea = Input.TextArea
const TreeNode = Tree.TreeNode

@connect(
  state => ({
    editInfoPending : state.Passport.editInfoPending,
    editInfoError   : state.Passport.editInfoError,
    editInfoMessage : state.Passport.editInfoMessage,
    auth            : state.Passport.auth,//  homeData
  }),
  dispatch => ({
    actions: bindActionCreators({ ...passportActions }, dispatch)
  })
)
@Form.create()
export default class QuickStartModal extends PureComponent {

  state = {
    disabled: true,
    alert: null
  }

  constructor (props) {
    super(props)
    this.state = {
      selectedKeys: props.auth.quickStart
    }
    this._Modal = null
    this._Form = null
  }
  
  componentWillReceiveProps (nextProps) {
    const { editInfoError, editInfoMessage } = nextProps
    if (editInfoError > 0 && editInfoMessage !== this.props.editInfoMessage) {
      this.setState({ alert: (
        <Alert
          style={{ margin: '0 40px 24px' }}
          message={editInfoMessage}
          type="error"
          showIcon
          key="aaa"
        />
      )})
    }
    if (editInfoError === 0 && editInfoMessage !== this.props.editInfoMessage) {
      this._Modal.handleOnCancel()
      notification.info({
        message: `系统提示`,
        description: `快速开始 / 便捷导航更新成功！`,
        duration: 8,
        placement: 'bottomRight'
      })
    }
  }
  
  render () {
    const { visible, onCancel, form, editInfoPending, auth, teams } = this.props
    const { getFieldDecorator } = form
    const { group } = auth
    let minLevel = 1001
    let maxLevel = group.level - 1
    const options = {
      ref: view => this._Modal = view,
      visible: visible,
      onCancel: onCancel,
      title: '快速开始 / 便捷导航',
      footer: [
        <Button
          onClick={() => this._Modal.handleOnCancel()}
          >
          取消
        </Button>,
        <Button
          type="primary"
          loading={editInfoPending}
          onClick={this.handleSubmit}
          >
          确定
        </Button>
      ],
      width: 600,
      height: 400,
      maskClosable: false
    }
    let siderMenus = getMenuOptions(auth)
    return (
      <Modal {...options}>
        <br />
        <Form 
          ref={ view => this._Form = view }
          layout="horizontal" 
          onSubmit={this.handleSubmit}
          >
          {editInfoPending ? null : (
            <QueueAnim component="div" type={['bottom', 'top']} leaveReverse>
              {this.state.alert ? this.state.alert : null}
            </QueueAnim>
          )}
          <FormItem 
            >
            <Tree
              checkable
              defaultExpandAll
              defaultCheckedKeys={this.state.selectedKeys}
              //checkedKeys={this.state.selectedKeys}
              //selectedKeys={this.state.selectedKeys}
              //onSelect={this.onSelect}
              onCheck={this.onCheck}
              >
              {siderMenus.map((item, i) => {
                return (
                  <TreeNode title={item.name} key={item.key} disabled>
                    {this.renderTreeNodeItem(item.children)}
                  </TreeNode>
                )
              })}
            </Tree>
          </FormItem>
        </Form>
      </Modal>
    )
  }

  renderTreeNodeItem = (children) => children.map((item, i) => {
    return (
      <TreeNode title={item.name} key={item.path} />
    )
  })

  onSelect = (selectedKeys, info) => {
    let _selectedKeys = this.state.selectedKeys
    let { eventKey } = info.node.props
    let eventKeyIndex = _selectedKeys.indexOf(eventKey)
    if (eventKeyIndex > -1) {
      _selectedKeys.splice(eventKeyIndex, 1)
    }
    else {
      _selectedKeys = [ ..._selectedKeys, eventKey]
    }
    let quickStart = []
    for (let item of _selectedKeys) {
      /^\//.test(item) && quickStart.push(item)
    }
    this.setState({ selectedKeys: quickStart })
  }

  onCheck = (checkedKeys, info) => {
    let quickStart = []
    for (let item of checkedKeys) {
      /^\//.test(item) && quickStart.push(item)
    }
    this.setState({ selectedKeys: checkedKeys })
  }
  
  handleSubmit = (e) => {
    e && e.preventDefault()
    this.props.actions.editInfo({ quickStart: this.state.selectedKeys })
  }
}

const getMenuOptions = (auth) => {
  let menuOptions = []
  for (let e of _.keys(menuSubs)) {
    let subTag = _.kebabCase(e.replace(/^(menuSub)/, ''))
    let subChildren = []
    let childrenData = menuSubs[e]['data']
    for (let item of childrenData) {
      let itemKey = item['key']
      let itemFlag = getPageFlag(`/${subTag}/${itemKey}`, 'access')
      !getFlagValue(auth, itemFlag.value, null) && subChildren.push({
        key: itemKey,
        name: item['name'],
        path: `/${subTag}/${itemKey}`
      })
    }
    subChildren.length > 0 && menuOptions.push({
      key: subTag,
      name: menuSubs[e]['name'],
      children: subChildren
    })
  }
  return menuOptions
}